﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using LitJson;

/// <summary>  
/// Ticket 的摘要说明  
/// </summary>  
public class Ticket
{
    public Ticket()
    {
        //  
        // TODO: 在此处添加构造函数逻辑  
        //  
    }

    public static string GetToken()
    {
        string to = "";
        string appid = "wx9800d99bbcd352dd";// "wx5955bd71e310a7b5";  
        string secret = "22288e4c51a352e9488390f2bec1aa7b";// "2d6b6ec95cde8bc2908713bde4c92434";  
        string parm = "grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";//2d6b6ec95cde8bc2908713bde4c92434  
        string url = "https://api.weixin.qq.com/cgi-bin/token";
        to = webRequestGet(url, parm);
        to = SubString1(to, "{\"access_token\":\"", "\",\"expires_in\":7200}");//acc_tonke  
        return to;
    }




    public static string GetewmPic(string scene_str)
    {
        string tocket = "";
        string pic = "";

        string b = GetToken();



        string poster = "{";
        poster += "\"action_name\": \"QR_LIMIT_STR_SCENE\",";
        poster += "\"action_info\": {";
        poster += "\"scene\": {";
        poster += "\"scene_str\": \"" + scene_str + "\"";
        poster += "}";
        poster += "}";
        poster += "}";//二维码永久请求格式  

        string tockes = GetPage("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + b + "", poster + "");
        if (tockes.IndexOf("ticket") > -1)
        {
            JsonData bejson = JsonMapper.ToObject(tockes);
            tocket = (String)bejson["ticket"];
            tocket = Uri.EscapeDataString(tocket);//TICKET必需UrlEncode  
        }


        string Picurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + tocket + "";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Picurl);
        req.Proxy = null;
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0";
        req.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2");
        req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        //HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();  

        System.Drawing.Image img = System.Drawing.Image.FromStream(req.GetResponse().GetResponseStream());
        string newfilename = "ewm_" + scene_str + ".jpg";//二维码图片路径  
                                                         // string filepath = @"D:\项目\wsl\ewmPic\" + newfilename;  
        string address = HttpContext.Current.Server.MapPath("/uploadimages/" + newfilename);
        img.Save(address);

        pic = "ewmPic/" + newfilename;

        return pic;


    }


    /// <summary>  
    /// Post 提交调用抓取  
    /// </summary>  
    /// <param name="url">提交地址</param>  
    /// <param name="param">参数</param>  
    /// <returns>string</returns>  
    public static string webRequestPostOAuth(string url)
    {
        //  byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);  

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
        req.Method = "GET";
        using (WebResponse wr = req.GetResponse())
        {
            //在这里对接收到的页面内容进行处理   

            Stream strm = wr.GetResponseStream();

            StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);

            string line;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line);
            }
            sr.Close();
            strm.Close();
            return sb.ToString();
        }
    }



    public static string SubString1(string sourceStr, string beginStr, string endStr)
    {
        int begin = sourceStr.IndexOf(beginStr);
        if (begin == -1) return "";
        int end = sourceStr.IndexOf(endStr, begin + beginStr.Length);
        if (end == -1 && end == begin + beginStr.Length) return "";

        return sourceStr.Substring(begin + beginStr.Length, end - begin - beginStr.Length);

    }
    /// <summary>  
    /// GET 提交调用抓取  
    /// </summary>  
    /// <param name="url">提交地址</param>  
    /// <param name="param">参数</param>  
    /// <returns>string</returns>  
    public static string webRequestGet(string url, string param)
    {
        byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param);
        req.Method = "GET";
        using (WebResponse wr = req.GetResponse())
        {
            //在这里对接收到的页面内容进行处理   

            Stream strm = wr.GetResponseStream();

            StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);

            string line;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line);
            }
            sr.Close();
            strm.Close();
            return sb.ToString();
        }
    }
    public static string GetPage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...  
        try
        {
            // 设置参数  
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据  
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求  
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页（html）代码  
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }




    public static void GetOrder(string order_id, ref string buyer_openid, ref string order_status, ref string product_name, ref string product_price, ref string product_count, ref string order_total_price)
    {
        DBHelper d = new DBHelper();
        string b = GetToken();

        buyer_openid = "";
        order_status = "";
        product_name = "";
        product_price = "";
        product_count = "";
        order_total_price = "";


        string poster = "{";
        poster += "\"order_id\": \"" + order_id + "\"";
        poster += "}";//订单信息  

        string tockes = GetPage("https://api.weixin.qq.com/merchant/order/getbyid?access_token=" + b + "", poster + "");
        if (tockes.IndexOf("order") > -1)
        {
            JsonData bejson = JsonMapper.ToObject(tockes);
            JsonData orderjson = bejson["order"];

            buyer_openid = orderjson["buyer_openid"].ToString();
            order_status = orderjson["order_status"].ToString();//订单状态 2-待发货, 3-已发货, 5-已完成
            product_name = orderjson["product_name"].ToString();
            product_price = orderjson["product_price"].ToString();//单价 单位分
            product_count = orderjson["product_count"].ToString();
            order_total_price = orderjson["order_total_price"].ToString();

        }
    }


}